<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/6/20
 * Time: 14:42
 */

namespace Biz\module\Classes;

use Biz\cache\ConfirmOrder as ConfirmOrderCache;
use Biz\cache\Coupon as cCoupon;
use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\model\activity\CouponRecord as mCouponRecord;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Biz\module\Classes\OutCoupon as clsOutCoupon;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\activity\MealInfo as sMealInfo;
use Biz\service\Activitys as sActivitys;
use Biz\tools\Amount;
use Doraemon\model\Member as mMember;
use Doraemon\service\User as sUser;
use Doraemon\tools\HhzClient;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log as tLog;
use Doraemon\tools\Log;


class Coupon
{
    use _Async;

    //用户中心我的优惠券列表的分类定义
    const CATE_ID_UNUSED = 1;
    const CATE_ID_USED = 2;
    const CATE_ID_EXPIRED = 3;

    //选择可用优惠券的列表，有两个TAB，TAB的定义
    const TAB_1 = 1;//可用
    const TAB_2 = 2;//不可用
    const TAB_3 = 3;//不可用原因详情

    //当前可用 与 凑单可用
    const TAB_CURRENT = 1;
    const TAB_TOGETHER_ORDER = 2;
    //当前可用 与 凑单可用 type
    const TAB_RECOMMEND_TYPE_CURRENT = 1;
    const TAB_RECOMMEND_TYPE_TOGETHER_ORDER = 2;

    const PROMO_INFO_1 = "你有一张<font color=\"#F0454C\">%s元 </font>优惠券<font  color=\"#F0454C\">%s</font>，<b><font color=\"#F0454C\">查看全部优惠券</font></b>";
    const PROMO_INFO_2 = "再买%s元减<font color=\"#F0454C\"> %s元</font>，<b><font color=\"#F0454C\">查看全部优惠券</font></b>";
    const PROMO_INFO_3 = "已减%s元，再买%s元减<font color=\"#F0454C\">%s元</font>，<b><font color=\"#F0454C\">查看全部优惠券</font></b>";
    const PROMO_INFO_4 = "已减%s元，<b><font color=\"#F0454C\">查看全部优惠券</font></b>";


    //显示的优惠券类型
    const TYPE_ID_1 = '1'; //全平台
    const TYPE_ID_2 = '2'; //限店铺
    const TYPE_ID_3 = '3'; //限品类
    const TYPE_ID_4 = '4'; //限商品使用
    const TYPE_ID_5 = '5'; //限品牌使用

    //优惠券兑换码 使用渠道
    const PULL_COUPON_INAPP = 'pull_coupon_inapp';
    const PULL_COUPON_INPARAGRAPH = 'pull_coupon_inparagraph';

    //优惠券失效原因分组
    const REASON_1 = 1;//因为优惠券剩余可领为0

    //批量优惠券默认分隔符
    const BATCH_COUPON_CODE_SEPARATOR = "-";

    //领取优惠券
    public static function receiveCoupon($uid, $couponId, $from = '', $couponCodeInfo = [], $payAmount = 0)
    {
        $nowTime = time();
        $nowdate = date('Y-m-d H:i:s');
        $config = cCoupon::getConfig($couponId);

        try {
            if (empty($config)) {
                throw new \Exception('优惠券不存在C1');
            }

            //渠道验证
            if ($config['channel'] == mCouponConfig::COUPON_CHANNEL_THE_PARAGRAPH && $from != self::PULL_COUPON_INPARAGRAPH) {
                throw new \Exception('优惠券不可领取C1');
            } else if ($config['channel'] != mCouponConfig::COUPON_CHANNEL_THE_PARAGRAPH && !in_array($from, ['', self::PULL_COUPON_INAPP])) {
                throw new \Exception('优惠券不可领取C1');
            }
            if ($couponCodeInfo && $couponCodeInfo['coupon_type'] != $config['coupon_code_type']) {
                throw new \Exception('优惠码错误，请检查后重试');
            }

            if (($config['status'] != mCouponConfig::STATUS_CAN_RECEIVE && $from != self::PULL_COUPON_INPARAGRAPH) || ($config['shop_id'] == 0 && !($config['start_show_time'] < $nowdate && $config['stop_show_time'] > $nowdate))) {
                throw new \Exception('优惠券不可领取C2');
            }

            $user = sUser::getUser($uid);
            if ($user['type'] == mMember::AUTH_USER_BRAND) {
                throw new \Exception('品牌用户不可领取');
            }

            if ($config['type_time'] == mCouponConfig::TYPE_TIME_STATIC) {
                $stopTime = strtotime($config['stop_time']);

                if ($stopTime < $nowTime) {
                    self::setCouponCannotReceive($couponId);

                    throw new \Exception('优惠券已过期C3');
                }
            }

            if ($from == self::PULL_COUPON_INPARAGRAPH) {
                $data = self::receiveParagraphCoupon($uid, $couponId, $config, $couponCodeInfo, $payAmount, $nowTime);
                if ($data) {
                    if (isset($config['exclude_goods_ids']) && $config['exclude_goods_ids']) {
                        $data['exclude_goods_ids'] = explode(',', $config['exclude_goods_ids']);
                    }
                    return $data;
                }
            }

            if ($config['status'] != mCouponConfig::STATUS_CAN_RECEIVE ) {
                throw new \Exception('优惠券不可领取C0');
            }

            self::increCouponCount($couponId);

            if ($config['receive_rule'] > 0) {
                $sum = mCouponRecord::getUserHasCouponSum($uid, $couponId);

                if ($sum >= $config['receive_rule']) {
                    throw new \Exception('该优惠券限领' . $config['receive_rule'] . '张C4');
                }
            }
            if ($couponCodeInfo && $couponCodeInfo['coupon_type'] == mCouponConfig::BATCH_COUPON_TYPE) {
                $result = cCoupon::setBatchCouponPulled($couponId, $couponCodeInfo['batch_coupon_code']);
                if ($result == -1) {
                    throw new \Exception('优惠码错误，请检查后重试');
                } elseif ($result == -2) {
                    throw new \Exception('该优惠码已使用');
                }
            }

        } catch (\Exception $e) {
            $msg = $e->getMessage();
            $line = $e->getLine();
            tLog::warning('领劵错误', [$msg, $line]);
            if ($from != self::PULL_COUPON_INAPP) {
                $msg = preg_replace('/C\d$/', '', $msg);
            }
            throw new \Exception($msg);
        }
        $data = self::formatConfigCoupon($config, $payAmount);
        $data = self::formatRecordData($data, $config, $couponCodeInfo, $nowTime);
        self::insertRecordData($uid, $couponId, $data);
        self::showFormatCoupon($data, $config);
        if ($data && isset($config['exclude_goods_ids']) && $config['exclude_goods_ids']) {
            $data['exclude_goods_ids'] = explode(',', $config['exclude_goods_ids']);
        }
        return $data;

    }


    private static function receiveParagraphCoupon($uid, $couponId, $config, $couponCodeInfo, $payAmount, $nowTime)
    {
//        if (bccomp($payAmount, $config['full_amount'], 2) < 0) {
//            throw new \Exception('商品金额满' . $config['full_amount'] . '元即可使用该优惠券');
//        }
        $unUsed = mCouponRecord::getUnUsed($uid, $couponId);
        //如果有未使用的优惠券  则判断是否需要改过期时间
        if ($unUsed) {
            $data = self::formatConfigCoupon($config, $payAmount);
            if ($config['type_time'] == mCouponConfig::TYPE_TIME_RELATIVELY) {
                $relativeSecond = $config['relative_days'] * 86400;
                $data['start_time'] = date('Y-m-d H:i:s', $nowTime - 3600);
                $data['stop_time'] = date('Y-m-d 23:59:59', $nowTime + $relativeSecond);
                mCouponRecord::update($data, ['uid' => $unUsed[0]['uid'], 'coupon_id' => $unUsed[0]['coupon_id']]);
            }
            $data = self::formatRecordData($data, $config, $couponCodeInfo, $nowTime);
            self::showFormatCoupon($data, $config);
            return $data;
        }
        return null;
    }

    private static function formatRecordData($data, $config, $couponCodeInfo, $nowTime)
    {
        //相对时间，那么需要在领取时计算优惠券有效期
        if ($config['type_time'] == mCouponConfig::TYPE_TIME_RELATIVELY) {

            $relativeSecond = $config['relative_days'] * 86400;

            $data['start_time'] = date('Y-m-d H:i:s', $nowTime);
            $data['stop_time'] = date('Y-m-d 23:59:59', $nowTime + $relativeSecond);
        }
        if ($couponCodeInfo) {
            if (isset($couponCodeInfo['batch_coupon_code'])) {
                $data['code'] = implode("-", [
                    $couponCodeInfo['coupon_code'],
                    $couponCodeInfo['batch_coupon_code']
                ]);
            } else {
                $data['code'] = $couponCodeInfo['coupon_code'];
            }
        }

        //unset掉一些不可插入的字段
        if (isset($data['type_desc'])) {
            unset($data['type_desc']);
            unset($data['type_id']);
        }

        return $data;
    }

    private static function insertRecordData($uid, $couponId, $data)
    {
        mCouponRecord::insertCoupon($uid, $couponId, $data);
        //计算优惠券领取数
        mCouponConfig::update(['received_count[+]' => 1], ['coupon_id' => $couponId]);
    }

    private static function increCouponCount($couponId)
    {
        $result = cCoupon::incrCouponCount($couponId);
        if ($result == -1) {
            self::setCouponCannotReceive($couponId, [], self::REASON_1);

            throw new \Exception('手慢了，优惠券已被抢光C5');
        }
    }


    private static function formatCouponCode($couponCode)
    {
        $formatData = [];
        $couponCode = str_replace("_", self::BATCH_COUPON_CODE_SEPARATOR, trim($couponCode));
        if (strpos($couponCode, self::BATCH_COUPON_CODE_SEPARATOR) !== false) {
            //批量类型优惠码
            $couponCodeArray = explode(self::BATCH_COUPON_CODE_SEPARATOR, $couponCode);
            if (count(array_filter($couponCodeArray)) == 2) {
                $formatData = [
                    'coupon_type' => mCouponConfig::BATCH_COUPON_TYPE,
                    'coupon_code' => strtoupper($couponCodeArray[0]),
                    'batch_coupon_code' => strtoupper($couponCodeArray[1])
                ];
            } else {
                $formatData = [
                    'coupon_type' => mCouponConfig::NORMAL_COUPON_TYPE,
                    'coupon_code' => $couponCode
                ];
            }
        } else {
            $formatData = [
                'coupon_type' => mCouponConfig::NORMAL_COUPON_TYPE,
                'coupon_code' => $couponCode
            ];
        }
        return $formatData;
    }


    //根据coupon_code领取优惠券
    public static function pullCoupon($uid, $couponCode, $skuToken = '', $from = self::PULL_COUPON_INAPP, $payAmount = 0)
    {
        $couponCodeInfo = self::formatCouponCode($couponCode);
        if ($couponCodeInfo['coupon_type'] == mCouponConfig::BATCH_COUPON_TYPE) {
            $couponId = cCoupon::getCouponCodeCache($couponCodeInfo['coupon_code']);
        } else {
            $couponId = cCoupon::getCouponCodeCache(strtoupper($couponCodeInfo['coupon_code']));
            if (!$couponId) {
                $couponId = cCoupon::getCouponCodeCache($couponCodeInfo['coupon_code']);
            }
        }

        if (empty($couponId)) {
            throw new \Exception('此兑换码无效');
        }

        try {
            $data = self::receiveCoupon($uid, $couponId, $from, $couponCodeInfo, $payAmount);

            $data['can_use'] = 0;

            if ($skuToken) {
                $data['can_use_tip'] = '兑换成功，当前订单不可用';

                $coupon = self::giveCouponIdCalCanUse($uid, $couponId, $skuToken, [],false);

                if (!empty($coupon[self::TAB_1])) {
                    $data['can_use'] = 1;
                    //当输入的couponcode是店铺券生成时则提示文案变动
                    $data['can_use_tip'] = '兑换成功，当前订单可用';

                }

                //哪些商品不可用提示
                if(!empty($coupon[self::TAB_3])){
                    $data['can_use_data'] = $coupon[self::TAB_3];
                    foreach($data['can_use_data'] as &$_v){
                        if(strlen($_v['msg']) > 5){
                            $data['can_use'] = 0;
                            $data['can_use_tip'] = '兑换成功，当前订单不可用';
                            break;
                        }
                    }
                }
            } else {
                $data['can_use'] = 1;
                $data['can_use_tip'] = '兑换成功';
            }

            if ($data['can_use'] > 0) {
                if ($data['assume'] == mCouponConfig::COUPON_ASSUME_SHOP) {
                    $shopInfo = mShopBasicInfo::getShopInfo($data['shop_id'], ['name']);

                    $data['can_use_tip'] = sprintf('兑换成功，请在购买 %s 店内商品时使用', $shopInfo['name']);
                }
            } else {
                if ($from == self::PULL_COUPON_INPARAGRAPH && isset($data['full_amount']) && $data['full_amount']) {
                    $data['msg'] = 'm:商品金额满' . $data['full_amount'] . '元即可使用该优惠券';
                }
            }


            return $data;
        } catch (\Exception $e) {

            $msg = $e->getMessage();

            preg_match('/C\d$/', $msg, $matches);

            if (!empty($matches[0])) {
                switch ($matches[0]) {
                    case 'C1':
                        $msg = '此兑换码无效';
                        break;
                    case 'C2':
                        $msg = '此兑换码已过期';
                        break;
                    case 'C5':
                        $msg = '此兑换码已被领光';
                        break;
                    case 'C3':
                        $msg = '此兑换码已过期';
                        break;
                    case 'C4':
                        $msg = '已兑换过此优惠券';
                        break;
                    default:
                        $msg = preg_replace('/C\d$/', '', $msg);
                        break;
                }
            }


            throw new \Exception($msg);
        }


    }

    public static function checkCouponCanDown($couponId, $assume)
    {
        $result = clsOutCoupon::checkCouponInOutCouponCantDown($couponId, $assume);

        if ($result !== true && $result > 0) {
            throw new \Exception('有进行中的站外H5领券活动，活动编号' . $result . '请联系 好好住 操作');
        }
    }

    //可以领取的优惠券列表
    public static function canReceiveList($uid, $goodsId, $limit, $shopId = 0)
    {

        if ($goodsId > 0) {
            //判断有正在进行中的限时抢的商品，排除在此次计算列表外
            $limitRobList = sActivitys::getCurrentLimitRobByGids([$goodsId]);

            if (in_array($goodsId, $limitRobList)) {
                return [];
            }

            //查询商品的品类
            $info = mGoodsBasicInfo::getLevel_1_2_CateIds($goodsId, true);
            $cateId = isset($info[$goodsId]) ? $info[$goodsId] : [];

            if (!empty($cateId)) {
                preg_match('/^(\d)-/', $cateId, $matches);
                $cateWhere = [
                    'cate_scope' => mCouponConfig::CATE_SCOPE_NOT_ALL,
                    'OR #1' => [
                        'AND #1' => [
                            'cate_ids[~]' => "|" . $cateId . "|",
                        ],
                        'AND #2' => [
                            'cate_ids[~]' => "|" . $matches[1] . '-0' . "|"
                        ]
                    ]

                ];
            }
        }

        $nowDate = date('Y-m-d H:i:s');
        $where = [
            'coupon_code' => '',
            'total_count[>]' => \Medoo\Medoo::raw('received_count'),
            'OR' => [
                'AND #1' => [
                    'shop_id' => 0,
                    'cate_scope' => mCouponConfig::CATE_SCOPE_ALL,
                    'type_time' => mCouponConfig::TYPE_TIME_RELATIVELY,
                    'status' => mCouponConfig::STATUS_CAN_RECEIVE,
                    'start_show_time[<]' => $nowDate,
                    'stop_show_time[>]' => $nowDate,
                ],
                'AND #2' => [
                    'shop_id' => 0,
                    'cate_scope' => mCouponConfig::CATE_SCOPE_ALL,
                    'type_time' => mCouponConfig::TYPE_TIME_STATIC,
                    'stop_time[>]' => date('Y-m-d H:i:s'),
                    'start_show_time[<]' => $nowDate,
                    'stop_show_time[>]' => $nowDate,
                    'status' => mCouponConfig::STATUS_CAN_RECEIVE,
                ],
            ],
            'ORDER' => ['coupon_id' => 'DESC']
        ];

        //查询限品类的优惠券
        if (isset($cateWhere)) {
            $where['OR']['AND #3'] = array_merge([
                'shop_id' => 0,
                'type_time' => mCouponConfig::TYPE_TIME_RELATIVELY,
                'status' => mCouponConfig::STATUS_CAN_RECEIVE,
                'start_show_time[<]' => $nowDate,
                'stop_show_time[>]' => $nowDate,
            ], $cateWhere);
            $where['OR']['AND #4'] = array_merge([
                'shop_id' => 0,
                'type_time' => mCouponConfig::TYPE_TIME_STATIC,
                'status' => mCouponConfig::STATUS_CAN_RECEIVE,
                'start_show_time[<]' => $nowDate,
                'stop_show_time[>]' => $nowDate,
            ], $cateWhere);
        }

        if ($limit > 0) {
            $where['LIMIT'] = $limit;
        }

        if ($shopId > 0) {
            $where['OR']['AND #7'] = [
                'shop_id' => $shopId,
                'cate_scope' => mCouponConfig::CATE_SCOPE_ALL,
                'type_time' => mCouponConfig::TYPE_TIME_STATIC,
                'stop_time[>]' => date('Y-m-d H:i:s'),
                'status' => mCouponConfig::STATUS_CAN_RECEIVE,
            ];
        }

        $list = mCouponConfig::select("*", $where);

        //查询此列表中，我已经领取的coupon
        $couponIds = array_column($list, 'coupon_id');

        $mineList = [];

        if ($uid > 0) {
            $mineList = mCouponRecord::select('*', [
                'uid' => $uid,
                'coupon_id' => $couponIds
            ]);
            $mineList = array_column($mineList, null, 'coupon_id');
        }

        //优惠券列表排序
        if (!empty($list)) {
            $fullAmountList = array_column($list, 'full_amount');
            $detractAmountList = array_column($list, 'detract_amount');
            $stopTimestampList = array_map(function ($v) {
                return strtotime($v);
            }, array_column($list, 'stop_time'));
            $addTimestampList = array_map(function ($v) {
                return strtotime($v);
            }, array_column($list, 'addtime'));

            array_multisort($fullAmountList, SORT_ASC, SORT_NUMERIC, $detractAmountList, SORT_DESC, SORT_NUMERIC,
                $stopTimestampList, SORT_ASC, SORT_NUMERIC, $addTimestampList, SORT_ASC, SORT_NUMERIC, $list);

        }

        $list = array_map(function ($v) use ($mineList) {

            $data = self::formatConfigCoupon($v);

            self::showFormatCoupon($data, $v, 'receive_list');

            $data['is_receive'] = 0;

            if (!empty($mineList[$v['coupon_id']])) {
                $data['is_receive'] = 1;
            }

            return $data;
        }, array_filter($list, function ($v) use ($goodsId) {

            if (empty($goodsId)) {
                return true;
            }
            //根据传来的商品GOODS ID判断该商品ID是否有不可使用的coupon
            return self::checkGoodsIdSupportCoupon($goodsId, $v['coupon_id']);

        }));

        return $list;
    }


    //商品详情页展示的可领优惠券列表
    public static function goodsTips($uid, $goodsId, $shopId = 0)
    {
        $user = sUser::getUser($uid);

        if ($user['type'] == mMember::AUTH_USER_BRAND) {
            return [];
        }


        $list = self::canReceiveList($uid, $goodsId, 0, $shopId);

        if (empty($list)) {
            return [];
        }

        return array_column(array_slice($list, 0, 3), 'title');
    }


    //我的优惠券列表
    public static function mineList($uid, $cateId, $filter = [], $needAll = false)
    {

        $nowTime = time();
        $where = ['uid' => $uid];

        if (!empty($filter)) {
            $where = array_merge($where, $filter);
        }

        switch ($cateId) {
            case self::CATE_ID_UNUSED:
                $where['status'] = mCouponRecord::COUPON_STATUS_UNUSED;
                if (!$needAll) {
                    $where['start_time[<=]'] = date('Y-m-d H:i:s', $nowTime);
                }
                $where['stop_time[>=]'] = date('Y-m-d H:i:s', $nowTime);
                $where['ORDER'] = ['stop_time' => 'DESC'];
                break;
            case self::CATE_ID_USED:
                $where['status'] = mCouponRecord::COUPON_STATUS_USED;
                $where['ORDER'] = ['use_time' => 'DESC'];
                break;
            case self::CATE_ID_EXPIRED:
                $where['OR'] = [
                    'AND #1' => [
                        'status' => mCouponRecord::COUPON_STATUS_UNUSED,
                        'stop_time[<=]' => date('Y-m-d H:i:s', $nowTime)
                    ],
                    'AND #2' => [
                        'status' => mCouponRecord::COUPON_STATUS_EXPIRED
                    ]
                ];
                break;
        }
        if (HhzClient::getClientType() != HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM) {
            //如果客户端为节选
            $where['type'] = mCouponConfig::COUPON_TYPE_DISCOVER;
        }


        $list = mCouponRecord::select_master('*', $where);

        if (empty($list)) {
            return [];
        }


        $nearNowTime = array_map(function ($v) {
            return strtotime($v);
        }, array_column($list, 'stop_time'));

        if ($cateId == self::CATE_ID_UNUSED) {
            array_multisort($nearNowTime, SORT_ASC, SORT_NUMERIC, $list);
        } elseif ($cateId == self::CATE_ID_EXPIRED) {
            array_multisort($nearNowTime, SORT_DESC, SORT_NUMERIC, $list);
        }


        $couponIds = array_column($list, 'coupon_id', 'coupon_id');

        $configWhere = ['coupon_id' => $couponIds];
        //判断来源
        $configWhere['channel'] = [
            mCouponConfig::COUPON_CHANNEL_APP,
            mCouponConfig::COUPON_CHANNEL_OUT_APP,
        ];
        if (HhzClient::getClientType() && HhzClient::getClientType() == HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM) {
            $configWhere['channel'] = mCouponConfig::COUPON_CHANNEL_THE_PARAGRAPH;
        }

        $configList = mCouponConfig::select(['assume', 'cate_scope', 'cate_ids', 'remark', 'channel', 'use_with_integral', 'coupon_id', 'goods_range', 'include_goods_ids', 'type', 'discount_level'], $configWhere);
        $configList = array_column($configList, null, 'coupon_id');

        $shopIds = array_filter(array_column($list, 'shop_id'));
        $shopList = mShopBasicInfo::getShopInfoList($shopIds, [
            'shop_id',
            'name'
        ]);


        $list = array_map(function ($v) use ($configList, $cateId, $nowTime, $shopList) {

            $data = [];
            if (isset($configList[$v['coupon_id']])) {
                $data = [
                    'coupon_id' => $v['coupon_id'],
                    'coupon_vid' => $v['coupon_vid'],
                    'title' => str_replace('.00', '', $v['title']),
                    'full_amount' => str_replace('.00', '', $v['full_amount']),
                    'detract_amount' => str_replace('.00', '', $v['detract_amount']),
                    'assume' => $v['assume'],
                    'shop_info' => [
                        'shop_id' => $v['shop_id'],
                        'shop_name' => !empty($shopList[$v['shop_id']]) ? sprintf('「%s」优惠券',
                            $shopList[$v['shop_id']]['name']) : '好好住平台券'
                    ],
                    'use_with_integral' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['use_with_integral'] : 0,
                    'type' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['type'] : 0,
                    'cate_scope' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['cate_scope'] : 0,
                    'cate_ids' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['cate_ids'] : 0,
                    'discount_level' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['discount_level'] : 0,
                    'channel' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['channel'] : 0,
                    'goods_range' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['goods_range'] : 0,
                    'include_goods_ids' => isset($configList[$v['coupon_id']]) ? $configList[$v['coupon_id']]['include_goods_ids'] : '',
                    'will_expired' => 0,
                    'end_time' => $v['stop_time'],
                    'start_time' => str_replace('-', '.', substr($v['start_time'], 0, 10)),
                    'stop_time' => str_replace('-', '.', substr($v['stop_time'], 0, 10)),
                    'is_used' => (strtotime($v['use_time']) > 0) ? 1 : 0,
                    'remark' => isset($configList[$v['coupon_id']]['remark']) ? $configList[$v['coupon_id']]['remark'] : '',
                ];

                //类型信息
                if ($configList[$v['coupon_id']]['assume'] == mCouponConfig::COUPON_ASSUME_HHZ) {
                    $data['type_id'] = self::TYPE_ID_1;
                    $data['type_desc'] = '全场通用';
                } elseif ($configList[$v['coupon_id']]['assume'] == mCouponConfig::COUPON_ASSUME_SHOP) {
                    $data['type_id'] = self::TYPE_ID_2;
                    $data['type_desc'] = '限店铺使用';
                }
                if ($configList[$v['coupon_id']]['cate_scope'] == mCouponConfig::CATE_SCOPE_NOT_ALL) {
                    $data['type_id'] = self::TYPE_ID_3;
                    $data['type_desc'] = '限品类使用';
                }


                //店铺券的使用规则
                if (empty($data['remark'])) {
                    if ($data['assume'] == mCouponConfig::COUPON_ASSUME_SHOP) {
                        switch ($configList[$v['coupon_id']]['goods_range']) {
                            case mCouponConfig::GOODS_RANGE_ALL:
                                $data['remark'] = '店铺全部商品通用，限时购及特殊商品不支持使用';
                                break;
                            case mCouponConfig::GOODS_RANGE_PART:
                                $data['remark'] = '店铺部分商品可用，限时购及特殊商品不支持使用';
                                break;
                        }
                    }
                }


                if ($cateId == self::CATE_ID_UNUSED) {
                    if ((strtotime($data['end_time']) - $nowTime) < 48 * 3600) {
                        $data['will_expired'] = 1;
                    }
                } elseif ($cateId == self::CATE_ID_EXPIRED) {
                    //如果是取得过期数据，那么因为过期数据是实时计算的，所以需要异步修改过期的状态为静态

                    if ($v['status'] != mCouponRecord::COUPON_STATUS_EXPIRED) {
                        self::detectExpiredCoupon($data);
                    }
                }

            }

            return $data;
        }, $list);

        return array_values(array_filter($list));

    }

    public static function detectExpiredCoupon($couponInfo)
    {
        self::_async($couponInfo);
    }

    public static function _async_detectExpiredCoupon($couponInfo)
    {


        //修改指定优惠券为过期态
        mCouponRecord::update(['status' => mCouponRecord::COUPON_STATUS_EXPIRED],
            ['coupon_vid' => $couponInfo['coupon_vid']]);
    }

    //将优惠券至为失效
    public static function setCouponCannotReceive($couponId, $where = [], $reason = '')
    {

        if ($reason == self::REASON_1) {
            clsOutCoupon::setOfflineByCouponId($couponId);
        }

        mCouponConfig::setCannotReceive($couponId, $where);
    }

    //给出最值得平台优惠券
    public static function getBestCouponSelect($uid, $skuBuyList = [])
    {
        $couponSelect = self::calCanUseCouponList($uid, $skuBuyList);

        if (empty($couponSelect[self::TAB_1]) || HhzClient::$client_type == HhzClient::APPTYPE_PARAGRAPH_MINIPROGRAM) {
            return [];
        }

        $couponSelect = array_shift($couponSelect[self::TAB_1]);

        if (!empty($couponSelect)) {
            return $couponSelect;
        }
    }


    //在订单确认页面展示优惠券可用和非可用列表
    public static function selectList($uid, $tabId = '', $skuToken = '', $couponId = 0, $skuBuyList = [], $sCouponListJson = '', $mealId = 0)
    {
        if (empty($skuToken) && empty($skuBuyList)) {
            return [];
        }

        if (!empty($skuToken)) {
            $skuBuyList = self::getSkuBuyListWithOrderSkuToken($uid, $skuToken);
            if (!empty($sCouponListJson)) {
                self::sCouponListToAssignSelectList($uid, $skuToken, $skuBuyList, $sCouponListJson);
            }
        }


        if (!empty($skuBuyList) && $mealId > 0) {

            self::calSkuBuyListAfterUseMealList($mealId, $skuBuyList);

        }

        $result = self::calCanUseCouponList($uid, $skuBuyList, $couponId);

        if(!empty($tabId)) {
            return $result[$tabId];
        }else{
            return $result;
        }
    }

    //给出一个coupon_id生成一个领券码
    public static function genCouponCode($couponId)
    {
        return IdParse::hashCouponId($couponId);
    }

    public static function calSkuBuyListAfterUseMealList($mealId, &$skuBuyList = [])
    {

        //build需要的列表
        $goodsBuyList = [];
        foreach ($skuBuyList as $skuId => $skuBuyInfo) {
            $goodsBuyList[$skuBuyInfo['goods_id']][] = [
                'sku_id' => $skuId,
                'ori_price' => $skuBuyInfo['buy_price'],
            ];
        }

        $mealList = sMealInfo::getMealGoodsPrice($mealId, $goodsBuyList);

        if (!empty($mealList)) {
            bcscale(2);
            foreach ($skuBuyList as $skuId => &$skuBuyInfo) {
                $buySumAmount = bcmul($skuBuyInfo['buy_price'], $skuBuyInfo['buy_num']);

                $skuBuyInfo['total_amount'] = isset($mealList['sku_price'][$skuId]) ? bcsub($buySumAmount,
                    $mealList['sku_price'][$skuId]['detract_price']) : $buySumAmount;
            }
        }
    }


    //给出一个coupon_id计算订单是否可用该优惠券如果可用则返回coupon信息，其中包括优惠金额
    public static function giveCouponIdCalCanUse($uid, $couponId, $skuToken = '', $skuBuyList = [], $isTab = true)
    {

        if($isTab) {
            $select = self::selectList($uid, self::TAB_1, $skuToken, $couponId, $skuBuyList);
            $coupon = $select ? array_shift($select) : [];
        }else{
            $select = self::selectList($uid, '', $skuToken, $couponId, $skuBuyList);
            $coupon = $select;
        }

        return $coupon;
    }

    //计算订单及sku使用的优惠券抵扣金额 TODO
    public static function calOrderSkuCouponDiscount(
        $uid,
        $couponId,
        $couponDiscount = 0,
        $skuToken = '',
        $skuBuyList = []
    )
    {

        $result = [];

        if ((empty($skuToken) && empty($skuBuyList)) || $couponDiscount == 0) {
            return [];
        }

        if (!empty($skuToken)) {
            $skuBuyList = self::getSkuBuyListWithOrderSkuToken($uid, $skuToken);
        }

        $checkGoods = self::checkGoodsIdsCanUseCoupon($skuBuyList, $couponId);
        $skuBuyList = isset($checkGoods['skuBuyList'])?$checkGoods['skuBuyList']:[];
        $noUseCoupon = isset($checkGoods['noUseCoupon'])?$checkGoods['noUseCoupon']:[];

        if (empty($skuBuyList)) {
            return [];
        }

        //计算此次下单的总额
        $sumAmount = array_sum(array_map(function ($v) {
            if (isset($v['total_amount'])) {
                return $v['total_amount'];
            } else {
                return $v['buy_num'] * $v['buy_price'];
            }
        }, $skuBuyList));

        if ($sumAmount == 0) {
            return [];
        }

        //按比例计算分摊的优惠金额
        $i = 1;
        $discountAmount = 0;
        $config = cCoupon::getConfig($couponId);
        if ($config && $config['type'] == mCouponConfig::COUPON_TYPE_DISCOUNT && $config['discount_level']) {
            $couponDiscount = bcsub($sumAmount, bcmul($sumAmount, $config['discount_level'] / 10, 2), 2);
        }
        $skuNum = count($skuBuyList);

        foreach ($skuBuyList as &$buyInfo) {

            if ($i == $skuNum) {

                $buyInfo['coupon_discount'] = Amount::format($couponDiscount - $discountAmount);


            } else {

                $amount = isset($buyInfo['total_amount']) ? $buyInfo['total_amount'] : ($buyInfo['buy_num'] * $buyInfo['buy_price']);

                $ratio = $amount / $sumAmount;

                $buyInfo['coupon_discount'] = Amount::format($ratio * $couponDiscount);

                $discountAmount += $buyInfo['coupon_discount'];
            }

            $i++;

        }

        $result = $skuBuyList;

        return $result;
    }


    //订单使用优惠券，订单创建成功之前调用
    //return    true  使用成功
    //return    false  使用失败
    public static function useACouponInOrder($uid, $parentOrderNo, $couponVId, $couponId)
    {

        $result = mCouponRecord::update([
            'use_time' => date('Y-m-d H:i:s'),
            'use_order_no' => $parentOrderNo,
            'status' => mCouponRecord::COUPON_STATUS_USED
        ], [
            'uid' => $uid,
            'coupon_vid' => $couponVId,
            'coupon_id' => $couponId,
            'status' => mCouponRecord::COUPON_STATUS_UNUSED,
            'use_order_no' => ''
        ]);

        if (is_object($result)) {

            if ($result->rowCount() > 0) {

                //优惠券使用次数增加
                mCouponConfig::update(['used_count[+]' => 1], ['coupon_id' => $couponId]);

                tLog::coupon_usecoupon_info('优惠券使用成功', [
                    'uid' => $uid,
                    'parent_order_no' => $parentOrderNo,
                    'coupon_vid' => $couponVId,
                    'coupon_id' => $couponId
                ]);

                return true;
            }
        }

        tLog::coupon_usecoupon_warning('优惠券使用失败', [
            'uid' => $uid,
            'parent_order_no' => $parentOrderNo,
            'coupon_vid' => $couponVId,
            'coupon_id' => $couponId
        ]);

        return false;

    }
    //订单取消，退优惠券
    //return    true  退成功
    //return    false 退失败
    public static function cancelACouponInOrder($uid, $parentOrderNo, $couponId, $couponVId)
    {
        $result = mCouponRecord::update([
            'use_time' => '0000-00-00 00:00:00',
            'use_order_no' => '',
            'status' => mCouponRecord::COUPON_STATUS_UNUSED
        ], [
            'uid' => $uid,
            'coupon_vid' => $couponVId,
            'use_order_no' => $parentOrderNo,
            'status' => mCouponRecord::COUPON_STATUS_USED,
        ]);

        if (is_object($result)) {

            if ($result->rowCount() > 0) {

                //优惠券使用次数减少
                mCouponConfig::update(['used_count[-]' => 1], ['coupon_id' => $couponId]);

                tLog::coupon_cancel_info('订单取消优惠券成功',
                    [
                        'uid' => $uid,
                        'coupon_vid' => $couponVId,
                        'use_order_no' => $parentOrderNo
                    ]);

                return true;
            }
        }

        tLog::coupon_cancel_info('订单取消优惠券失败',
            [
                'uid' => $uid,
                'coupon_vid' => $couponVId,
                'use_order_no' => $parentOrderNo
            ]);

        return false;
    }


    public static function cacheCouponConfig($couponId, $configInfo = [])
    {

        cCoupon::setConfig($couponId, $configInfo);
    }

    protected static function sCouponListToAssignSelectList($uid, $skuToken, &$skuBuyList = [], $sCouponListJson = '')
    {
        bcscale(2);
        $jsonData = json_decode($sCouponListJson, true);

        if (empty($jsonData)) {
            return [];
        }


        //对确认订单页其他店铺使用的优惠券信息处理
        $sCouponList = [];

        foreach ($jsonData as $value) {
            $sCouponList[$value['shop_id']] = $value['coupon_info']['coupon_id'];
        }


        //获取优惠券抵扣金额
        $couponIds = array_values($sCouponList);

        $sCouponConfig = mCouponConfig::select([
            'coupon_id',
            'detract_amount'
        ], ['coupon_id' => $couponIds]);

        $sCouponConfig = array_column($sCouponConfig, 'detract_amount', 'coupon_id');


        //获取每个店铺的购买信息
        foreach ($sCouponList as $shopId => $couponId) {

            $skuShopBuyList = self::getSkuBuyListWithOrderSkuToken($uid, $skuToken, $shopId);

            $skuShopCalDiscount = self::calOrderSkuCouponDiscount($uid, $couponId, $sCouponConfig[$couponId], '',
                $skuShopBuyList);

            if (!empty($skuShopCalDiscount)) {
                foreach ($skuShopCalDiscount as $skuId => $calDiscount) {
                    $skuBuyList[$skuId]['total_amount'] = bcsub(bcmul($calDiscount['buy_price'],
                        $calDiscount['buy_num']), $calDiscount['coupon_discount']);
                }
            }
        }

    }

    /*
       * 根据指定用户,给定的sku购买价格和购买数计算可用优惠券列表，不包括运费
       *
       * skuBuyList结构参考
       *                  {
       *                      "125": {            //SKU ID
       *                          "goods_id":1,
       *                          "buy_price": 11.5,      //购买价格
       *                          "buy_num": 2            //购买数量
       *                          },
       *                      "251": {            //SKU ID
       *                          "goods_id":2,
       *                          "buy_price": 22.5,
       *                           "buy_num": 3
       *                          }
       *                  }
       */
    protected static function calCanUseCouponList($uid, $skuBuyList = [], $couponId = 0, $shopId = 0)
    {
        //获取skuId
        $result = [
            self::TAB_1 => [],
            self::TAB_2 => [],
            self::TAB_3 => [],
        ];


        $checkGoods = self::checkGoodsIdsCanUseCoupon($skuBuyList, $couponId);
        $skuBuyList = isset($checkGoods['skuBuyList'])?$checkGoods['skuBuyList']:[];
        $noUseCoupon = isset($checkGoods['noUseCoupon'])?$checkGoods['noUseCoupon']:[];

        //找到当前用户下的所有有效且未使用的优惠券列表

        $filterCouponId = ($couponId > 0) ? ['coupon_id' => $couponId] : [];
        $filterShopId = ($shopId > 0) ? ['shop_id' => $shopId] : ['shop_id' => 0];
        $mineList = self::mineList($uid, self::CATE_ID_UNUSED, array_merge($filterCouponId, $filterShopId));

        if (empty($mineList)) {
            return $result;
        }

        //判断返回的优惠券是否需要排除掉不支持的goodsID
        $result = self::calBestGroupCouponList($skuBuyList, $mineList, $shopId);

        if (!empty($result[self::TAB_1])) {

            //按照可见金额最大倒序
            $maxDetractAmount = array_column($result[self::TAB_1], 'detract_amount');

            $nearNowTime = array_map(function ($v) {
                return strtotime($v);
            }, array_column($result[self::TAB_1], 'end_time'));


            array_multisort($maxDetractAmount, SORT_DESC, SORT_NUMERIC, $nearNowTime, SORT_ASC, SORT_NUMERIC,
                $result[self::TAB_1]);
        }

        if(!empty($noUseCoupon)){
            $result[self::TAB_3] = $noUseCoupon;
        }

        return $result;
    }

    protected static function getSkuBuyListWithOrderSkuToken($uid, $skuToken = '', $shopId = 0)
    {

        $cacheJson = ConfirmOrderCache::getConfirmInfo($uid, $skuToken);

        $cacheInfo = json_decode($cacheJson, true);

        if (empty($cacheInfo)) {
            return [];
        }

        $skuBuyList = [];

        foreach ($cacheInfo['list'] as $info) {

            if ($shopId > 0) {

                if ($info['shop_info']['shop_id'] == $shopId) {
                    foreach ($info['sku_list'] as $skuInfo) {
                        $skuBuyList[$skuInfo['sku_id']] = [
                            'goods_id' => $skuInfo['goods_id'],
                            'buy_price' => $skuInfo['actual_price'],
                            'buy_num' => $skuInfo['buy_num']
                        ];
                    }

                    break;
                }
            } else {
                foreach ($info['sku_list'] as $skuInfo) {
                    $skuBuyList[$skuInfo['sku_id']] = [
                        'goods_id' => $skuInfo['goods_id'],
                        'buy_price' => $skuInfo['actual_price'],
                        'buy_num' => $skuInfo['buy_num']
                    ];
                }
            }


        }


        return $skuBuyList;
    }

    protected static function formatConfigCoupon($couponConfig, $payAmount = 0)
    {
        $couponConfig['full_amount'] = floatval($couponConfig['full_amount']);
        $couponConfig['detract_amount'] = floatval($couponConfig['detract_amount']);
        $couponConfig['discount_level'] = floatval($couponConfig['discount_level']);
        $title = '';
        if ($couponConfig['type'] == mCouponConfig::COUPON_TYPE_DISCOVER) {
            $title = sprintf('满%s减%s', $couponConfig['full_amount'], $couponConfig['detract_amount']);
        } else if ($couponConfig['type'] == mCouponConfig::COUPON_TYPE_DISCOUNT) {
            $title = sprintf('满%s打%s折', $couponConfig['full_amount'], $couponConfig['discount_level']);
            if ($payAmount) $couponConfig['detract_amount'] = bcsub($payAmount, bcmul($payAmount, $couponConfig['discount_level'] / 10, 2), 2);
        }
        $data = [
            'coupon_id' => $couponConfig['coupon_id'],
            'title' => $title,
            'full_amount' => $couponConfig['full_amount'],
            'detract_amount' => $couponConfig['detract_amount'],
            'discount_level' => $couponConfig['discount_level'],
            'assume' => $couponConfig['assume'],
            'include_goods_ids' => !empty($couponConfig['include_goods_ids'])?explode(',', $couponConfig['include_goods_ids']):'',
            'exclude_goods_ids' => !empty($couponConfig['exclude_goods_ids'])?explode(',', $couponConfig['exclude_goods_ids']):'',
            'include_brand_ids' => !empty($couponConfig['include_brand_ids'])?explode(',', $couponConfig['include_brand_ids']):'',
        ];

        //类型信息
        if ($couponConfig['assume'] == mCouponConfig::COUPON_ASSUME_HHZ) {
            $data['type_id'] = self::TYPE_ID_1;
            $data['type_desc'] = '全场通用';
        } elseif ($couponConfig['assume'] == mCouponConfig::COUPON_ASSUME_SHOP) {
            $data['type_id'] = self::TYPE_ID_2;
            $data['type_desc'] = '限店铺使用';
        }
        if ($couponConfig['cate_scope'] == mCouponConfig::CATE_SCOPE_NOT_ALL) {
            $data['type_id'] = self::TYPE_ID_3;
            $data['type_desc'] = '限品类使用';
        }
        if ($couponConfig['cate_scope'] == mCouponConfig::CATE_SCOPE_GOODS) {
            $data['type_id'] = self::TYPE_ID_4;
            $data['type_desc'] = '限商品使用';
        }
        if ($couponConfig['cate_scope'] == mCouponConfig::CATE_SCOPE_BRAND) {
            $data['type_id'] = self::TYPE_ID_3;
            $data['type_desc'] = '限品牌使用';
        }


        if ($couponConfig['type_time'] == mCouponConfig::TYPE_TIME_STATIC) {
            $data['start_time'] = $couponConfig['start_time'];
            $data['stop_time'] = $couponConfig['stop_time'];
        }

        if ($couponConfig['shop_id'] > 0) {
            $data['shop_id'] = $couponConfig['shop_id'];
        }

        return $data;
    }

    protected static function showFormatCoupon(&$data, $couponConfig = [], $from = '')
    {

        //判断是否即将过期
        if ((strtotime($data['stop_time']) - time()) < 48 * 3600) {
            $data['will_expired'] = 1;
        } else {
            $data['will_expired'] = 0;
        }

        $data['start_timestamp'] = strtotime($data['start_time']);
        $data['stop_timestamp'] = strtotime($data['stop_time']);

        $data['start_time'] = str_replace('-', '.', substr($data['start_time'], 0, 10));
        $data['stop_time'] = str_replace('-', '.', substr($data['stop_time'], 0, 10));

        if ($from == 'receive_list') {
            if ($couponConfig['type_time'] == mCouponConfig::TYPE_TIME_STATIC) {
                $data['time_range_desc'] = $data['start_time'] . '-' . $data['stop_time'];
            } elseif ($couponConfig['type_time'] == mCouponConfig::TYPE_TIME_RELATIVELY) {
                $data['time_range_desc'] = sprintf('领取后%s天内有效', $couponConfig['relative_days']);
            }


        }

        //类型信息
        if ($couponConfig['assume'] == mCouponConfig::COUPON_ASSUME_HHZ) {
            $data['type_id'] = self::TYPE_ID_1;
            $data['type_desc'] = '全场通用';
        } elseif ($couponConfig['assume'] == mCouponConfig::COUPON_ASSUME_SHOP) {
            $data['type_id'] = self::TYPE_ID_2;
            $data['type_desc'] = '限店铺使用';
        }
        if ($couponConfig['cate_scope'] == mCouponConfig::CATE_SCOPE_NOT_ALL) {
            $data['type_id'] = self::TYPE_ID_3;
            $data['type_desc'] = '限品类使用';
        }
        if ($couponConfig['cate_scope'] == mCouponConfig::CATE_SCOPE_GOODS) {
            $data['type_id'] = self::TYPE_ID_4;
            $data['type_desc'] = '限商品使用';
        }
        if ($couponConfig['cate_scope'] == mCouponConfig::CATE_SCOPE_BRAND) {
            $data['type_id'] = self::TYPE_ID_5;
            $data['type_desc'] = '限品牌使用';
        }


    }

    protected static function checkGoodsIdsCanUseCoupon($skuBuyList = [], $couponId = 0)
    {

        $skuIds = array_keys($skuBuyList);

        //判断有正在进行中的限时抢的商品，排除在此次计算列表外
        $limitRobList = sActivitys::getCurrentLimitRobBySkuIds($skuIds);
Log::debug('判断是否能使用优惠券', compact('limitRobList', 'skuBuyList    ', 'couponId'));
        //有限时抢的进入到不可用列表
        $noUseCoupon = [];
        $skuBuyList = array_filter($skuBuyList, function ($v, $k) use ($limitRobList, $couponId, &$noUseCoupon) {
            //无限时抢的
            if (!in_array($k, $limitRobList)) {

                //判断优惠券是否支持
                if ($couponId > 0) {

                    $noUseCoupon[] = [
                        'goods_id' => $v['goods_id'],
                        'msg' => self::checkGoodsIdSupportCoupon($v['goods_id'], $couponId, true)
                    ];

                    return self::checkGoodsIdSupportCoupon($v['goods_id'], $couponId);

                }
                return true;
            }

            return false;
        }, ARRAY_FILTER_USE_BOTH);

        return [
            'skuBuyList' => $skuBuyList,
            'noUseCoupon' => $noUseCoupon,
        ];
    }

    /**
     * 由于每个优惠券有不支持的商品列表，那么需要找到一个最佳优惠券与订单组合的最佳组合
     *
     */
    protected static function calBestGroupCouponList($skuBuyList, $mineList, $shopId = 0)
    {
        $bestGroup = [];
        foreach ($mineList as $coupon) {
            $supportSum = 0;
            foreach ($skuBuyList as $skuId => $item) {
                if (self::checkGoodsIdSupportCoupon($item['goods_id'], $coupon['coupon_id'])) {

                    if (isset($item['total_amount'])) {
                        $supportSum += $item['total_amount'];
                    } else {
                        $supportSum += bcmul($item['buy_price'], $item['buy_num'], 2);
                    }
                }
            }

            if ($coupon['type'] == mCouponConfig::COUPON_TYPE_DISCOUNT) {
                //满折优惠券
                $coupon['detract_amount'] = bcsub($supportSum, bcmul($supportSum, $coupon['discount_level'] / 10, 2), 2);
            }
            if ($supportSum >= $coupon['full_amount']) {
                $bestGroup[self::TAB_1][] = $coupon;
            } else {
                $bestGroup[self::TAB_2][] = $coupon;
            }
        }

        if (empty($bestGroup)) {
            return [];
        }


        return $bestGroup;

    }

    /*
     * return true   支持
     *        false  不支持
     */
    protected static function checkGoodsIdSupportCoupon($goodsId, $couponId, $getInfo = false)
    {
        $checkCouponSupport = cCoupon::checkSupportGoodsId($goodsId, $couponId);

        //如果第一步判断都不支持，则直接返回false
        if (!$checkCouponSupport) {
            if ($getInfo) {
                return '该商品无法使用此优惠券';
            }else {
                return false;
            }
        }

        $couponInfo = cCoupon::getConfig($couponId);

        //如果优惠券是限制品类的，则需要判断品类是否支持
        if ($couponInfo['cate_scope'] == mCouponConfig::CATE_SCOPE_NOT_ALL) {

            //限制品类的优惠券需要判断的地方
            $cateIds = mGoodsBasicInfo::getLevel_1_2_CateIds($goodsId);

            //是否二级分类有支持
            //$rule1 = isset($cateIds[$goodsId]) ? '|' . $cateIds[$goodsId]['category_id'] . '-' . $cateIds[$goodsId]['second_category_id'] . '|' : '';
            $rule1 = isset($cateIds[$goodsId]) ?  '-'. $cateIds[$goodsId]['second_category_id'] . '|': '';
            if (!empty($rule1) && strpos($couponInfo['cate_ids'], $rule1) !== false) {
                return true;
            }else {
                if ($getInfo) {
                    return '该商品分类无法使用此优惠券';
                }
            }

            //如果二级分类没有支持，那么则查询一级分类
//            $rule2 = isset($cateIds[$goodsId]) ? '|' . $cateIds[$goodsId]['category_id'] . '-0|' : '';
//
//            if (!empty($rule2) && strpos($couponInfo['cate_ids'], $rule2) !== false) {
//                return true;
//            }

            return false;

        } else if($couponInfo['cate_scope'] == mCouponConfig::CATE_SCOPE_GOODS){
            //是否限制商品使用的券
            if(in_array($goodsId, explode(',', $couponInfo['include_goods_ids']))){
                return true;
            }else {
                if ($getInfo) {
                    return '该商品无法使用此优惠券';
                }
            }

            return false;
        } else if($couponInfo['cate_scope'] == mCouponConfig::CATE_SCOPE_BRAND){
            //是否限制品牌使用的券
            $brand_id = mGoodsBasicInfo::get('brand_id', ['goods_id'=>$goodsId]);
            if(in_array($brand_id, explode(',', $couponInfo['include_brand_ids']))){
                return true;
            }else {
                if ($getInfo) {
                    return '该商品品牌无法使用此优惠券';
                }
            }

            return false;
        } else {
            return true;
        }

    }

}